package com.xiaoxi.bms.service.menu.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaoxi.bms.common.exception.BMSException;
import com.xiaoxi.bms.domain.menu.BMSMenu;
import com.xiaoxi.bms.domain.menu.vo.BMSMoveMenu;
import com.xiaoxi.bms.mapper.menu.BMSMenuMapper;
import com.xiaoxi.bms.service.menu.BMSMenuService;
import com.xiaoxi.bms.service.menu.BMSMoveMenuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @ClassName BMSMoveAfterMenuServiceImpl
 * @Description
 * @Author xiaoxi
 * @Date 2022/10/6 10:33
 * @Version 1.0
 */
@Service("BMSMenu_after")
@Slf4j
public class BMSMoveAfterMenuServiceImpl implements BMSMoveMenuService {


    @Resource
    private BMSMenuMapper bmsMenuMapper;

    @Resource
    private BMSMenuService bmsMenuService;

    @Override
    public void move(BMSMoveMenu bmsMoveMenu) throws BMSException {

        log.info("结点：{} 在：{} 结点之前", bmsMoveMenu.getCurrentId(), bmsMoveMenu.getDropId());

        // 被移动结点
        BMSMenu dropBmsMenu = bmsMenuMapper.selectById(bmsMoveMenu.getDropId());
        Long dropBMSMenuParentId = dropBmsMenu.getParentId();

        // 移动结点
        BMSMenu currentBmsMenu = bmsMenuMapper.selectById(bmsMoveMenu.getCurrentId());


        List<BMSMenu> bmsMenuList = queryMenuListByParentId(dropBMSMenuParentId);
        int order = 100;
        // 更新orderBy 用于 菜单展示 排序
        for (BMSMenu menu : bmsMenuList) {

            menu.setOrderBy(order++);

            // 如果某个结点 和 被移动结点 相等， 说明位置到了
            if (menu.getId().equals(dropBmsMenu.getId())) {
                currentBmsMenu.setOrderBy(order++);
                currentBmsMenu.setParentId(dropBMSMenuParentId);
            }

        }
        // 将当前结点加入 list  用于后面的批量更新
        bmsMenuList.add(currentBmsMenu);

        bmsMenuService.updateBatchById(bmsMenuList,1000);

    }


    /**
     * 查询父节点 所有子节点
     *
     * @param parentId
     * @return
     */
    private List<BMSMenu> queryMenuListByParentId(Long parentId) {
        QueryWrapper<BMSMenu> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", parentId);
        return bmsMenuMapper.selectList(queryWrapper);
    }

}
